/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import {
  pickedFaceData,
  pickedLineData,
  pickedModelData,
  pickedVertexData,
} from '@amcax/base';
import { previewer } from '@app-cad/module';
import {
  NumberInputFormat,
  PickInputRJSFFormat,
} from '@app-cad/common/components/command-form/constants';
import { PickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useTools } from '@app-cad/common/hooks/useTools';
import { CurvedBaseCommand, CurvedCmdDialogParams } from '@app-cad/types';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import i18n from 'i18next';
import { useEffect, useState } from 'react';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { getIdOfPickedObj } from '@app-cad/common/utils/render';

type objDataType =
  | pickedModelData
  | pickedFaceData
  | pickedLineData
  | pickedVertexData;

type FormDataType = {
  target?: objDataType;
  frame?: pickedModelData;
  scalex: number;
  scaley: number;
  scalez: number;
};

function AffineDialog({ title, onClose, props }: CurvedCmdDialogParams) {
  const { picker } = useTools();

  const initData = {
    scalex: 1,
    scaley: 1,
    scalez: 1,
  };

  const [formData, setFormData] = useState<FormDataType>(initData);

  useEffect(() => {
    preview();
  }, [formData]);

  useAsyncEffect(async () => {
    if (props == null) {
      setFormData(initData);
      return;
    }

    const { frame, scale } = props.params;

    const [scalex = 1, scaley = 1, scalez = 1] = scale ?? [];

    await initEditDependency([frame, props.baseid]);
    setFormData({
      frame: picker.generatePickObjByPickID(frame) as pickedModelData,
      target: picker.generatePickObjByPickID(props.baseid),
      scalex,
      scaley,
      scalez,
    });
  }, [props?.shape]);

  const isFormDataValid = () => {
    const { target, scalex, scaley, scalez } = formData;

    return target != null && scalex > 0 && scaley > 0 && scalez > 0;
  };

  const checkAndFinishDraw = async () => {
    if (!isFormDataValid()) return;

    await execute();
    onClose();
  };

  const preview = async () => {
    if (!isFormDataValid()) {
      previewer.clear();
      return;
    }

    await execute(true);
  };

  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      target: {
        type: 'string',
        format: PickInputRJSFFormat.PickALL,
      },
      frame: {
        type: 'string',
        format: PickInputRJSFFormat.PickFrame,
      },
      scalex: {
        type: 'number',
        title: 'x方向比率',
        format: NumberInputFormat.Real,
      },
      scaley: {
        type: 'number',
        title: 'y方向比率',
        format: NumberInputFormat.Real,
      },
      scalez: {
        type: 'number',
        title: 'z方向比率',
        format: NumberInputFormat.Real,
      },
    },
  };

  const { initEditDependency, initingEdit, confirmCommand, isLoading } =
    useCommand('cmd-affine', {
      onClose,
      finishDraw: checkAndFinishDraw,
      commandName: 'Affine',
      editDxid: props?.shape,
    });

  const execute = async (preview = false) => {
    const { target, frame, scalex, scaley, scalez } = formData;
    const params = {
      frame: frame?.idInfo?.o,
      scale: [scalex, scaley, scalez],
    };

    await confirmCommand(
      {
        o: getIdOfPickedObj(target),
        a: params,
      },
      preview,
    );
  };

  return (
    <PickableCommandForm
      disabled={initingEdit}
      onClose={onClose}
      title={title}
      schema={schema}
      formData={formData}
      submitLoading={isLoading}
      onChange={(v) => {
        setFormData(v);
      }}
      extraUiSchema={{
        target: {
          'ui:placeholder': '请输入被缩放元素',
          'ui:disabled': props != null,
          'ui:autofocus': true,
        },
        frame: {
          'ui:placeholder': '缩放坐标系（可选）',
        },
        scalex: {
          'ui:placeholder': '请输入缩放比例',
        },
        scaley: {
          'ui:placeholder': '请输入缩放比例',
        },
        scalez: {
          'ui:placeholder': '请输入缩放比例',
        },
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
      isFormDataValid={isFormDataValid()}
    />
  );
}

export const cmdCurveAffine: CurvedBaseCommand = {
  id: 'CmdAffine',
  label: 'command.affine',
  icon: 'commands/curved/affinity',
  create: (label: string, onClose: () => void, props: any) => (
    <AffineDialog
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
    />
  ),
};
